/**
 * Copyright (c) 2017 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
 * @author 张丁方
 * @CreateTime 2017-3-31 13:32:13
 */
package com.hyyt.shopjsp.order.service.imp;

import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.hyyt.shopjsp.util.common.EnumUtils;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.hyyt.shopjsp.basic.pojo.BasicUsers;
import com.hyyt.shopjsp.logistics.pojo.ShopCityCourier;
import com.hyyt.shopjsp.order.dao.ShopOrdersDAO;
import com.hyyt.shopjsp.order.dao.ShopOrdersOplogDAO;
import com.hyyt.shopjsp.order.pojo.ShopOrders;
import com.hyyt.shopjsp.order.pojo.ShopOrdersOplog;
import com.hyyt.shopjsp.order.pojo.ShopShipping;
import com.hyyt.shopjsp.order.service.IShopOrdersService;
import com.hyyt.shopjsp.util.json.JSONFormatDate;
import com.hyyt.shopjsp.util.number.SerialNumberUtil;

@Service
public class ShopOrdersService implements IShopOrdersService {
    private static  final Logger logger = Logger.getLogger(IShopOrdersService.class);

    @Resource
    private ShopOrdersDAO shopOrdersDAO;
    @Resource
    private ShopOrdersOplogDAO shopOrdersOPLogDAO;
    @Resource
    private ShopShippingService shopShippingService;

    /**
     * 保存SHOP_订单
     *
     * @param shopOrders SHOP_订单
     * @return 保存后的SHOP_订单
     */
    @Override
    public void saveShopOrders(ShopOrders shopOrders) {
        shopOrdersDAO.insert(shopOrders);
    }

    /**
     * 更新SHOP_订单
     *
     * @param shopOrders SHOP_订单
     * @return 更新后的SHOP_订单
     */
    @Override
    public void updateShopOrders(ShopOrders shopOrders) {
        shopOrdersDAO.update(shopOrders);
    }

    /**
     * 删除指定ID的SHOP_订单
     *
     * @param id SHOP_订单ID
     */
    @Override
    public void deleteShopOrders(Integer id) {
        shopOrdersDAO.delete(id);
    }

    /**
     * 删除指定ID集合的SHOP_订单
     *
     * @param ids SHOP_订单ID集合
    */
    public void deleteShopOrders(Collection<Integer> ids){
        shopOrdersDAO.batchDelete(ids);
    }

    /**
     * 根据ID加载一个SHOP_订单
     *
     * @param id SHOP_订单ID
     * @return SHOP_订单
     */
    @Override
    public ShopOrders loadShopOrders(Integer id) {
        return shopOrdersDAO.load(id);
    }

    /**
    * 查询所有的SHOP_订单，通常有最多取30000条记录的限制
    *
    * @return 所有的SHOP_订单，通常有最多取30000条记录的限制
    */
    @Override
    public List<ShopOrders> queryAllShopOrders() {
        return shopOrdersDAO.queryAll();
    }

    /**
     * 查询SHOP_订单
     *
     * @param params 查询参数，为key-value形式
     * @return SHOP_订单集合
     */
    @Override
    public List<ShopOrders> queryShopOrders(Map<String, Object> params) {
        return shopOrdersDAO.query(params);
    }

    /**
     * 查询SHOP_订单
     *
     * @param params   查询参数，没有则传null,分页参数key为“sortColumns”
     * @param startRow 起始行数（不含起始行的数据）
     * @param rowSize  要查询记录数
     * @return SHOP_订单集合
     */
    @Override
    public List<ShopOrders> queryShopOrders(Map<String, Object> params, int startRow, int rowSize) {
        return shopOrdersDAO.query(params, startRow, rowSize);
    }

    /**
     * 统计SHOP_订单
     *
     * @param params 查询参数，没有则传null,分页参数key为“sortColumns”
     * @return 结果集记录数
     */
    @Override
    public int countShopOrders(Map<String, Object> params) {
        return shopOrdersDAO.count(params);
    }

    /**
     * 更改订单已发货状态(走物流公司)
     * @param orders
     * @param shipping
     * @param users
     * @return
     */
	@Override
	public ShopOrders saveOrUpdateChangeShipments(ShopOrders orders, ShopShipping shipping, BasicUsers users) {
		//修改订单
		ShopOrders order=new ShopOrders();
		order =shopOrdersDAO.load(orders.getOrdersId());
		order.setSendType(1);
		order.setOrdersState(4);
		order.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		shopOrdersDAO.update(order);
		//插入日志
		ShopOrdersOplog ordersOPLog=new ShopOrdersOplog();
		ordersOPLog.setOrdersId(order.getOrdersId());
		ordersOPLog.setOrdersNo(order.getOrdersNo());
		ordersOPLog.setOperatorTime(new Timestamp(System.currentTimeMillis()));
		ordersOPLog.setOrdersOperateState(4);
		ordersOPLog.setOoperatorId(users.getUsersId());//操作人id
		ordersOPLog.setOoperatorSource("1");//1、后台用户；2、后台系统；3、前台顾客；
		ordersOPLog.setOperatorName(users.getTrueName());//操作人name
		ordersOPLog.setComments("已发货");
		shopOrdersOPLogDAO.insert(ordersOPLog);//保存订单日志
		//物流信息
		SerialNumberUtil serialNumberUtill = new SerialNumberUtil();
		ShopShipping shopShipping =new ShopShipping();
		shopShipping=shipping;
		shopShipping.setShippingSn(serialNumberUtill.shippingSnNumber());//生成发货编号
		shopShipping.setOrdersId(orders.getOrdersId());
		shopShipping.setCreateDate(new Date());
		shopShippingService.saveShopShipping(shopShipping);
		return order;
	}

	/**
	 * 更改订单已发货状态(走同城快递)
	 * @param orders
	 * @param citycourier
	 * @param users
	 * @return
	 */
	@Override
	public ShopOrders saveOrUpdateChangeShipments(ShopOrders orders, ShopCityCourier citycourier, BasicUsers users) {
		//修改订单
		ShopOrders order=new ShopOrders();
		order =shopOrdersDAO.load(orders.getOrdersId());
		order.setSendType(2);
		order.setOrdersState(4);
		order.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		shopOrdersDAO.update(order);
		//插入日志
		ShopOrdersOplog ordersOPLog=new ShopOrdersOplog();
		ordersOPLog.setOrdersId(order.getOrdersId());
		ordersOPLog.setOrdersNo(order.getOrdersNo());
		ordersOPLog.setOperatorTime(new Timestamp(System.currentTimeMillis()));
		ordersOPLog.setOrdersOperateState(4);
		ordersOPLog.setOoperatorId(users.getUsersId());//操作人id
		ordersOPLog.setOoperatorSource("1");//1、后台用户；2、后台系统；3、前台顾客；
		ordersOPLog.setOperatorName(users.getTrueName());//操作人name
		ordersOPLog.setComments("已发货");
		shopOrdersOPLogDAO.insert(ordersOPLog);//保存订单日志
		//物流信息
		SerialNumberUtil serialNumberUtil = new SerialNumberUtil();
		ShopShipping shipping =new ShopShipping();
		shipping.setShippingSn(serialNumberUtil.shippingSnNumber());
		shipping.setCode("tongcheng");
		shipping.setDeliverySn(citycourier.getCityCourierId()+"");
		shipping.setOrdersId(orders.getOrdersId());
		shipping.setCreateDate(new Timestamp(System.currentTimeMillis()));
		Map<String, Object> jsonMap = new HashMap<String, Object>();// 定义map
		jsonMap.put("cityCourierId", citycourier.getCityCourierId());
		jsonMap.put("cityCourierName", citycourier.getCityCourierName());
		jsonMap.put("responsibleAreas", citycourier.getResponsibleAreas());
		jsonMap.put("phone", citycourier.getPhone());
		jsonMap.put("address", citycourier.getAddress());
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new JSONFormatDate(EnumUtils.DataFormat.Y_M_D.getValue()));
		JSONObject jo = JSONObject.fromObject(jsonMap, jsonConfig);
		shipping.setExpressInfo(jo.toString());
		shopShippingService.saveShopShipping(shipping);
		return order;
	}

	/**
	 * 更改订单正在配送状态
	 * @return
	 */
	@Override
	public ShopOrders saveOrUpdateChanggeOrdersState(String ordersId,BasicUsers basicUsers) {
		ShopOrders shopOrders =new ShopOrders();
		shopOrders=shopOrdersDAO.load(Integer.parseInt(ordersId));
		shopOrders.setOrdersState(3);
		shopOrders.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		shopOrdersDAO.update(shopOrders);
		//插入日志
		ShopOrdersOplog shopOrdersOPLog=new ShopOrdersOplog();
		shopOrdersOPLog.setOrdersId(shopOrders.getOrdersId());
		shopOrdersOPLog.setOrdersNo(shopOrders.getOrdersNo());
		shopOrdersOPLog.setOperatorTime(new Timestamp(System.currentTimeMillis()));
		shopOrdersOPLog.setOrdersOperateState(3);
		shopOrdersOPLog.setOoperatorId(basicUsers.getUsersId());//操作人id
		shopOrdersOPLog.setOoperatorSource("1");//1、后台用户；2、后台系统；3、前台顾客；
		shopOrdersOPLog.setOperatorName(basicUsers.getTrueName());//操作人name
		shopOrdersOPLog.setComments("已配货");
		shopOrdersOPLogDAO.insert(shopOrdersOPLog);
		return shopOrders;
	}

	/**
	 * 查询订单统计模块订单数量
	 * @param params
	 * @return
	 */
	@Override
	public int ordersCollectiveCount(Map<String,Object> params){
		return shopOrdersDAO.count("ordersCollectiveCount",params);
	}

	/**
	 * 根据条件查询订单统计集合
	 * @param params
	 * @return
	 */
	@Override
	public List<Map<String,Object>> ordersCollectiveList(Map<String,Object> params,int startRow, int rowSize){
		return shopOrdersDAO.query("ordersCollectiveList",params,startRow, rowSize);
	}

	/**
	 * 根据条件查询订单统计集合 方法重载，用于导出excel使用
	 * @param params
	 * @return
	 */
	@Override
	public List<Map<String,Object>> ordersCollectiveList(Map<String,Object> params){
		return shopOrdersDAO.query("ordersCollectiveList",params);
	}
}